var $newMemberTaable=$("#newMember")
$(function () {
    $('.datepicker').datepicker({
        language: "zh-CN",
        autoclose: true,
        clearBtn: true,
        todayHighlight: true,
        format: "yyyy-mm-dd"
    });
    customerIntentionInit();
    getMonth()

})


function getMonth(){
        $.getJSON("https://mgapi.dcrm.cn/hr/report/selectCallMonth", function (data) {
            var monthListHtml = '<option value="">全部</option>';
            data.map(function (item) {
                monthListHtml += '<option value="' + item.call_month + '">' + item.call_month + '</option>';
            });
            $("#monthList").html("");
            $('#monthList').append(monthListHtml);
            $('#monthList').selectpicker('refresh').on('changed.bs.select', function (e, clickedIndex, isSelected, previousValue) {      // 内容变更触发
                $newMemberTaable.bootstrapTable('refreshOptions', {pageNumber: 1, queryParams: queryParams,});
            });
        });
}
function queryParams(params) {
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式
    params.callMonth=$("#monthList").val()
    return params;
}

function customerIntentionInit(){
    //先销毁表格
    $newMemberTaable.bootstrapTable('destroy');
    $newMemberTaable.bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        url: 'https://mgapi.dcrm.cn/hr/report/selectPage',//请求地址
        //url: 'http://127.0.0.1:8087/hr/report/selectPage',//请求地址
        method: 'post',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: false,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'tatolHour',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'formId',
        idField: 'formId',
        pageSize: 50,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: "[50,100]",//可供选择的每页的行数
        queryParams: queryParams,//查询参数
        columns: [
            {title: '分公司', field: 'companyName', align: 'left', valign: 'middle'},
            {title: '姓名', field: 'accountName', align: 'left', valign: 'middle'},
            {title: '外呼量', field: 'callCount', align: 'left', valign: 'middle'},
            {title: '接通量', field: 'callAcceptCount', align: 'left', valign: 'middle'},
            {title: '通话时长', field: 'callHourCount', align: 'left', valign: 'middle'},
            {title: '通话均长', field: 'callAvgCount', align: 'left', valign: 'middle'},
            {title: '60s以内通话次数', field: 'inSixNumber', align: 'left', valign: 'middle'},
            {title: '60s以内通话时长', field: 'inSixCount', align: 'left', valign: 'middle'},
            {title: '60s-90s通话次数', field: 'sixNineNumber', align: 'left', valign: 'middle'},
            {title: '60s-90s通话时长', field: 'sixNineCount', align: 'left', valign: 'middle'},
            {title: '90s以上通话次数', field: 'onNineNumber', align: 'left', valign: 'middle'},
            {title: '90s以上通话时长', field: 'onNineCount', align: 'left', valign: 'middle'},
            {title: '外出拜访量', field: 'visitCount', align: 'left', valign: 'middle'}, //,sortable: true
            {title: '月份', field: 'callMonth', align: 'left', valign: 'middle'},
        ],
        responseHandler: function (result) {
            // if (result.code == "000000"){
            //     var obj = {
            //         "rows": result.data,
            //         "total": result.totalRecords
            //     };
            // } else {
            //     var obj = {
            //         "total": 0,
            //         "rows": [],
            //     }
            // }
            var obj = {
                "rows": result.list,

                "total": result.totalRecords,
            };
            return obj;
        },
        onLoadSuccess: function () {
            //加载成功时执行
            $("[data-toggle='tooltip']").tooltip();//加这个是为了让操作列的提示图标显示在上方
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    })
}

function timeSelect(th,type) {
    $(th).addClass('active-second')
    $(th).siblings().removeClass('active-second')
    $("#dateType").val(type)
    if(type==''){
        // if(){}
        // $('#customInput').css('display','block');
        if($("#customInput").is(":hidden")){
            $('#customInput').show();
        }else{
            $('#customInput').hide();
        }

    }else{
        // $('#customInput').css('display','none');
        $('#customInput').hide();
        $('#startTm').val('');
        $('#endTm').val('');
        $newMemberTaable.bootstrapTable('refresh');
    }


}


function exportExcel(){
    var paramsData = {
       callMonth:$("#monthList").val()
    }
    // json转url参数
    var parseParam = function(param, key) {
        var paramStr = '';
        if (param instanceof String || param instanceof Number || param instanceof Boolean) {
            paramStr += '&' + key + '=' + param;
        } else {
            $.each(param, function(i) {
                var k = key == null ? i : key + (param instanceof Array ? '[' + i + ']' : '.' + i);
                paramStr += '&' + parseParam(this, k);
            });
        }
        return paramStr.substr(1);
    };
    var that = this;
    paramsData = parseParam(paramsData);

    var page_url = 'https://mgapi.dcrm.cn/hr/report/exportExcel?'+paramsData;
    //var page_url = 'http://127.0.0.1:8087/hr/report/exportExcel?'+paramsData;
    var req = new XMLHttpRequest();
    req.open("Get", page_url, true);
    req.responseType = "blob";
    req.onreadystatechange = function () {
        if (req.status === 200 && req.readyState === 4) {
            // var filename = $(that).data('filename');
            if (typeof window.chrome !== 'undefined') {
                // Chrome version
                var link = document.createElement('a');
                link.href = window.URL.createObjectURL(req.response);
                link.download = '通话分析.xlsx';
                link.click();
            } else if (typeof window.navigator.msSaveBlob !== 'undefined') {
                // IE version
                var blob = new Blob([req.response], { type: 'application/force-download' });
                window.navigator.msSaveBlob(blob, '通话分析.xlsx');
            } else {
                // Firefox version
                var file = new File([req.response], '通话分析.xlsx', { type: 'application/force-download' });
                window.open(URL.createObjectURL(file));
            }
            //$btn.button('toggle');
            //$btn.button('reset');
        }
    };
    req.send();
}

$("#customDateBtn").on('click',function () {
    $newMemberTaable.bootstrapTable('refresh');
})